import Vue from 'vue'
import Vuex from 'vuex'

// import Vuex from '../vuex/index'

// 一般插件都是 函数，可以传参
const plugin = () => {
  return (store) => {
    store.subscribe((type, state) => {
      let local = JSON.parse(localStorage.getItem('aa'))
      if (local) {
        store.replaceState(local)
      }
      store.subscribe((type, state) => {
        localStorage.setItem('aa', JSON.stringify(state))
      })
    })
  }
}


Vue.use(Vuex)

const store = new Vuex.Store({ // options
  plugins: [plugin()],
  // strict: true, 严格模式
  state: { // 共享状态
    age: 18,
    a: { // 模块里的值会重新定义到全局，覆盖
      age: 5000
    }
  },
  getters: { // 计算属性，可以根据状态计算出 一个新状态  computed
    getAge(state) {
      return state.age - 5
    }
  },
  mutations: { // 同步更改   唯一更改状态的方式（严格模式下）
    changeAge(state, payload) {
      state.age = payload // 载荷
    }
  },
  actions: { // 异步更改
    // 方法调用都写在 action 中
    changeAge({commit}, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit('changeAge', payload)
          resolve(payload)
        }, 1000)
      })
    }
  },
  modules: {
    a: {
      namespaced: true,
      state: {
        aAge: 200
      },
      mutations: {
        changeAge(state, payload) {
          state.aAge = payload
        }
      },
      modules: {
        c: {
          namespaced: true,
          state: {
            cAge: 400
          },
          mutations: {
            changeAge(state, payload) {
              state.cAge = payload
            }
          }
        }
      }
    },
    b: {
      namespaced: true,
      state: {
        bAge: 300
      },
      mutations: {
        changeAge(state, payload) {
          state.bAge = payload
        }
      }
    }
  }
})


export default store